<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="header">
          <span>用户管理</span>
          <el-button type="primary" v-if="userType == 9" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="icon_path" label="头像" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.icon_path" :src="getIconUrl(scope.row.icon_path)" style="width: 30px; height: 30px;" :preview-src-list="[getIconUrl(scope.row.icon_path)]" />
            <span v-else>未上传</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="category" label="类别">
          <template #default="scope">
            {{ formatCategory(scope.row.category) }}
            <el-tag v-if="scope.row.category == 3" type="info" size="small" style="margin-left: 5px;">
              {{ formatSecType(scope.row.sec_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="scope">
            <el-switch v-model="scope.row.is_active" disabled />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" v-if="userType == 9" link @click="handleEdit(scope.row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增用户' : '编辑用户'" width="500px">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username" v-if="dialogType === 'add'">
          <el-input v-model="formData.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item v-if="userType == 9" label="类别" prop="category">
          <el-select v-model="formData.category" placeholder="请选择类别" @change="handleCategoryChange">
            <el-option 
              v-for="option in categoryOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.category === 3" label="二级权限" prop="sec_type">
          <el-select v-model="formData.sec_type" placeholder="请选择二级权限">
            <el-option label="教务老师" :value="0" />
            <el-option label="顾问老师" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.category === 3" label="简介" prop="desc">
          <el-input 
            v-model="formData.desc" 
            type="textarea" 
            :rows="4"
            placeholder="请输入老师简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            v-model:file-list="iconList"
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            accept=".jpg,.jpeg,.png,.webp"
            :on-change="handleIconChange"
          >
            <el-button type="primary">点击选择头像</el-button>
          </el-upload>
          <el-image v-if="currentIconUrl" :src="currentIconUrl" style="width: 80px; height: 80px; margin-top: 10px;" />
        </el-form-item>
        <el-form-item v-if="formData.category === 2" label="学生手机号" prop="student_phone">
          <el-input v-model="formData.student_phone" placeholder="请输入学生手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button v-if="userType == 9" @click="handleDeActive">注销</el-button>
        <el-button v-if="userType == 9" @click="handleReActive">恢复</el-button>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/user'
import { STATIC_RESOURCE_URL } from '../../config'
import api from '../../api'

export default {
  name: 'UserList',
  components: {
    Plus
  },
  setup() {
    const router = useRouter()
    const users = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const loading = ref(false)
    const userStore = useUserStore()
    
    const searchForm = reactive({
      username: '',
      name: ''
    })
    
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const userType = ref(0)
    const formRef = ref(null)
    const formData = reactive({
      id: '',
      username: '',
      password: '',
      name: '',
      phone: '',
      category: '',
      sec_type: 0,
      desc: '',
      icon_path: '',
      student_phone: ''
    })
    const iconList = ref([])

    // 类别选项
    const categoryOptions = [
      { label: '小程序用户', value: 0 },
      { label: '学员', value: 1 },
      { label: '家长', value: 2 },
      { label: '老师', value: 3 },
      { label: '管理员', value: 9 }
    ]
    
    // 格式化类别
    const formatCategory = (value) => {
      const option = categoryOptions.find(opt => opt.value === Number(value))
      return option ? option.label : '未知类别'
    }
    
    // 格式化二级权限
    const formatSecType = (value) => {
      return value === 1 ? '顾问老师' : '教务老师'
    }
    
    // 处理类别变化
    const handleCategoryChange = (value) => {
      // 如果不是老师类型，重置二级权限和简介
      if (value !== 3) {
        formData.sec_type = 0
        formData.desc = ''
      }
    }

    // 当前图标URL
    const currentIconUrl = computed(() => {
      if (iconList.value.length > 0) {
        return URL.createObjectURL(iconList.value[0].raw)
      }
      if (formData.icon_path) {
        return getIconUrl(formData.icon_path)
      }
      return ''
    })

    // 获取图标URL
    const getIconUrl = (iconPath) => {
      // 这里假设后端提供了获取图标的API或静态文件服务
      return `${STATIC_RESOURCE_URL}${iconPath}`
    }
    
    // 表单验证规则
    const formRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择类别', trigger: 'change' }
      ],
      student_phone: [
        { required: formData.category === 2, message: '请输入学生手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
      ]
    }
    
    // 加载用户列表
    const loadUsers = async () => {
      loading.value = true
      userType.value = userStore.user?.category
      try {
        const response = await api.get('/chance/users', {
          params: {
            skip: (currentPage.value - 1) * pageSize.value,
            limit: pageSize.value,
            ...searchForm
          }
        })
        users.value = response
        // 假设后端返回了总数，如果没有，这里可能需要额外的API调用来获取总数
        if (searchForm.username || searchForm.name) {
          // 在实际项目中，这里应该调用一个获取过滤后总数的API
          total.value = Math.min(response.length + (currentPage.value - 1) * pageSize.value, 1000)
        } else {
          // 如果没有搜索条件，可以使用简单的处理
          total.value = response.length + (currentPage.value - 1) * pageSize.value
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 查询
    const handleSearch = () => {
      currentPage.value = 1
      loadUsers()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      loadUsers()
    }
    
    // 新增用户
    const handleAdd = () => {
      dialogType.value = 'add'
      // 重置表单
      Object.keys(formData).forEach(key => {
        formData[key] = ''
      })
      iconList.value = []
      dialogVisible.value = true
    }

    // 处理图标选择变化
    const handleIconChange = (file) => {
      // 处理图标文件变化
    }
    
    // 编辑用户
    const handleEdit = (id) => {
      dialogType.value = 'edit'
      // 获取用户信息
      api.get(`/chance/users/${id}`).then(response => {
        Object.assign(formData, response)
        // 深拷贝响应数据
        const userData = JSON.parse(JSON.stringify(response))
        // 确保category字段是数字类型
        if (userData.category !== undefined && userData.category !== null) {
          userData.category = Number(userData.category)
        }
        // 设置学生手机号（如果有）
        if (userData.student_phone) {
          userData.student_phone = userData.student_phone
        }
        Object.assign(formData, userData)
        dialogVisible.value = true
      }).catch(error => {
        ElMessage.error('获取用户信息失败')
      })
    }
    
    // 提交表单
    const handleSubmit = async () => {
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const formDataToSend = new FormData()
            // 添加图标（如果有）
            if (iconList.value.length > 0) {
              formDataToSend.append('icon', iconList.value[0].raw)
            }
            formDataToSend.append('name', formData.name)
            formDataToSend.append('password', formData.password)
            formDataToSend.append('phone', formData.phone)
            formDataToSend.append('category', formData.category)
            // 只有当类别是老师时，才添加二级权限和简介
            if (formData.category === 3) {
              formDataToSend.append('sec_type', formData.sec_type)
              formDataToSend.append('desc', formData.desc || '')
            } else {
              formDataToSend.append('sec_type', 0)
              formDataToSend.append('desc', '')
            }
            // 只有当类别是家长时，才添加学生手机号
            if (formData.category === 2 && formData.student_phone) {
              formDataToSend.append('student_phone', formData.student_phone)
            }
            
            if (dialogType.value === 'add') {
              formDataToSend.append('username', formData.username)
              await api.post('/chance/users/', formDataToSend)
              ElMessage.success('新增用户成功')
            } else {
              await api.put(`/chance/users/${formData.id}`, formDataToSend)
              ElMessage.success('编辑用户成功')
            }
            dialogVisible.value = false
            handleCancel()
            loadUsers()
          } catch (error) {
            ElMessage.error(dialogType.value === 'add' ? '新增用户失败' : '编辑用户失败')
          }
        }
      })
    }

    // 取消操作
    const handleCancel = () => {
      dialogVisible.value = false
      // 清理表单数据
      if (formRef.value) {
        formRef.value.resetFields()
      }
      iconList.value = []
    }

    // 删除用户
    const handleDeActive = async () => {
      if (dialogType.value === 'edit') {
        try {
          await api.post(`/chance/users/deactivate/${formData.id}`)
          ElMessage.success('用户已注销')
          dialogVisible.value = false
          loadUsers()
        } catch (error) {
          ElMessage.error('注销用户失败')
        }
      }
    }

    // 恢复用户
    const handleReActive = async () => {
      if (dialogType.value === 'edit') {
        try {
          await api.post(`/chance/users/reactivate/${formData.id}`)
          ElMessage.success('用户已恢复')
          dialogVisible.value = false
          loadUsers()
        } catch (error) {
          ElMessage.error('恢复用户失败')
        }
      }
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadUsers()
    }
    
    const handleCurrentChange = (current) => {
      currentPage.value = current
      loadUsers()
    }
    
    onMounted(() => {
      loadUsers()
    })
    
    return {
      users,
      total,
      currentPage,
      pageSize,
      loading,
      searchForm,
      dialogVisible,
      dialogType,
      userType,
      formRef,
      formData,
      formRules,
      categoryOptions,
      iconList,
      currentIconUrl,
      getIconUrl,
      handleIconChange,
      formatCategory,
      formatSecType,
      handleCategoryChange,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleSubmit,
      handleCancel,
      handleDeActive,
      handleReActive,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.user-list {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  display: inline-block;
}
</style>